import moment from 'moment'

// 引入中文
import 'moment/locale/zh-cn'
// 设置中文
moment.locale('zh-cn')
import adapter from '@/render/adapter'
import { myList as myListNoLogin, list as getResult } from '@/management/api/dataform-result'
import { RuleMatch } from '@/common/logicEngine/RulesMatch'

const VOTE_INFO_KEY = 'voteinfo'
// const router = useRouter()
export default {
  // 初始化
  init(
    { commit, dispatch },
    { bannerConf, baseConf, bottomConf, dataConf, skinConf, submitConf, metaData }
  ) {
    // 根据初始的schema生成questionData, questionSeq, rules, formValues, 这四个字段
    const { questionData, questionSeq, rules, formValues } = adapter.generateData({
      bannerConf,
      baseConf,
      bottomConf,
      dataConf,
      skinConf,
      submitConf
    })

    // 将数据设置到state上
    commit('assignState', {
      questionData,
      questionSeq,
      rules,
      bannerConf,
      baseConf,
      bottomConf,
      dataConf,
      skinConf,
      submitConf,
      formValues,
      metaData
    })
    // 获取已投票数据
    dispatch('initResultData')
  },
  // 用户输入或者选择后，更新表单数据
  changeData({ commit }, data) {
    commit('changeFormData', data)
  },
  // 初始化数据的数据
  async initResultData({ state, commit }) {
    // const questionData = state.questionData
    const surveyPath = state.surveyPath
    // console.log(questionData)
    // const fieldList = []

    // for (const field in questionData) {
    //   const { type } = questionData[field]
    //   if (/vote/.test(type)) {
    //     fieldList.push(field)
    //   }
    // }

    // if (fieldList.length <= 0) {
    //   return
    // }
    try {
      // if (window.$app?.user?.token) {
        // localStorage.removeItem(VOTE_INFO_KEY)
      const voteRes = await getResult({
        condition:{
          formId: surveyPath,
          batchCode: state.batchCode
        },
        formId: surveyPath,
        batchCode: state.batchCode
      })

      // console.log(voteRes)
      if (voteRes?.serverResult?.resultCode === '200') {
        // localStorage.setItem(
        //   VOTE_INFO_KEY,
        //   JSON.stringify({
        //     ...voteRes.result
        //   })
        // )
        commit('setFormResult', voteRes?.result?.list)
        // commit('setVoteMap', voteRes.result)
        // console.log('voteRes.result', state.dataConf)
        // console.log('voteRes.result', voteRes.result.list)
        if (voteRes?.result?.list?.length > 0) {
          let myResultList = voteRes?.result?.list
          state.dataConf.dataList.forEach((item) => {
            item.value = item.value || ''
            // console.log('item', item)
            let idx = myResultList.findIndex((itm) => itm.attrId === item.attrId)
            if (idx > -1) {
              const data = {
                key: item.attrId,
                value: myResultList[idx].dataFormResult
              }
              commit('changeFormData', data)
            }
          })
        }
      }
      // }
    } catch (error) {
      console.log(error)
    }
  },
  updateVoteData({ state, commit }, data) {
    const { key: questionKey, value: questionVal } = data
    // 更新前获取接口缓存在localStorage中的数据
    const localData = localStorage.getItem(VOTE_INFO_KEY)
    const voteinfo = JSON.parse(localData)
    const currentQuestion = state.questionData[questionKey]
    const options = currentQuestion.options
    const voteTotal = voteinfo?.[questionKey]?.total || 0
    let totalPayload = {
      questionKey,
      voteKey: 'total',
      voteValue: voteTotal
    }
    options.forEach((option) => {
      const optionhash = option.hash
      const voteCount = voteinfo?.[questionKey]?.[optionhash] || 0
      // 如果选中值包含该选项，对应voteCount 和 voteTotal  + 1
      if (
        Array.isArray(questionVal) ? questionVal.includes(optionhash) : questionVal === optionhash
      ) {
        const countPayload = {
          questionKey,
          voteKey: optionhash,
          voteValue: voteCount + 1
        }
        totalPayload.voteValue += 1
        commit('updateVoteMapByKey', countPayload)
      } else {
        const countPayload = {
          questionKey,
          voteKey: optionhash,
          voteValue: voteCount
        }
        commit('updateVoteMapByKey', countPayload)
      }
      commit('updateVoteMapByKey', totalPayload)
    })
  },

  async initRuleEngine({ commit }, ruleConf) {
    const ruleEngine = new RuleMatch(ruleConf)
    commit('setRuleEgine', ruleEngine)
  }
}
